#include "CONFIG.H"
#include "NVIC.H"
#include "SWITCH.H"
#include "GPIO.H"
#include "DELAY.H"
#include "USB.H"
#include "usb_req_class.h"
#include "KEYBOARD.H"

u16 last_state = 0x0000;

u8 key_map[][4] = 
{
 {0x14 ,0x1A ,0x08 ,0x15},         //	Q				W				  E				R
 {0x04 ,0x16 ,0x07 ,0x09},         //	A				S				  D				F
 {0x00 ,0x06 ,0x19 ,0x2A},         //LShift			C				  V		    Backspace
 {0x00 ,0x00 ,0x00 ,0x2C},         //LCtrl			LENTER		LAlt		Space        
};     

void USER_CALL_DOWN(u8 row,u8 col){
		     
}

void USER_CALL_UP(u8 row,u8 col){
	
}

void scan_and_send(){
	u8 row,col,date = 2;
	u8 keys[8] = {0};
  last_state = KEYBOARD_scan();
	
	if(IF_KEY_SET(3, 0)) keys[0] |= 0x01; // LCtrl
	if(IF_KEY_SET(2, 0)) keys[0] |= 0x02; // LShift
	if(IF_KEY_SET(3, 2)) keys[0] |= 0x04; // LAlt
	if(IF_KEY_SET(3, 1)) keys[0] |= 0x08; // LGui
	
	for(row = 0 ; row < 4 ;row++){
		for(col = 0 ; col < 4 ;col++){
			u8 user_set = key_map[row][col];
			
			if(last_state == 0x0000) continue;
			
			if(IF_KEY_SET(row,col)){
				keys[date++] = user_set;
				if(date > 7) break;
			}
	  }
	}
	usb_my_keyboard(keys);
}
                           
void main(){     	
	EAXSFR();                       
	
	usb_init();
	KEYBOARD_init();
	
	EA = 1;
	while(1){
		scan_and_send();
		
		delay_ms(10);
	}
}